import { find } from 'lodash'
import moment from 'moment'
import { message, Upload } from 'ant-design-vue'
import { v4 as uuidv4 } from 'uuid'

import i18n from '@/locales/index' 
const { t } = i18n.global
export const getUId = () => {
  return uuidv4().split('-')[0]
}
export const getToken = () => {
  return localStorage.getItem('token') || ''
}
export const getLang = () => {
  let lang = localStorage.getItem('locale')
  return  lang || 'zh_cn '
}

export const firstLevelMenuItem = (menus, value) => {
  return find(menus, (item) => item.path === value)
}
export const getAllMenuItem = (list, path) => {
  for (let i in list) {
    list[i]
    if (list[i].path == path) {
      return [list[i]]
    }
    if (list[i].children) {
      let node = getAllMenuItem(list[i].children, path);
      if (node !== undefined) {
        return node.concat(list[i])
      }
    }
  }
}


export const getLocalStorage = (name) => {
  return localStorage.getItem(name) ? JSON.parse(localStorage.getItem(name)) : null
}
/**
 * 清空本地存储
 * @param options {keepItem: [key: '本地存储不用清除的名称']}
 *
 */
export const clearLocalStorage = (options) => {
  for (let i = localStorage.length - 1; i >= 0; i--) {
    const key = localStorage.key(i)
    if (key === null) {
      continue
    }
    let keep = false
    if (options && options.keepItems) {
      for (const keepItem of options.keepItems) {
        if (keepItem.key === key) {
          keep = true
          break
        }
      }
    }
    if (!keep) {
      localStorage.removeItem(key)
    }
  }
}
// 清除指定的缓存
export const clearSpecifiedLocalStorage = () => {
  let clearArray = ['token', 'user', 'menu', 'buttonMenuList', 'hangerLineList', 'unlocakPage', 'lockModalVisible', 'unlocakPage', 'currentLineStatus', 'currentLine', 'autoScreenLockTime']
  clearArray.forEach(key => {
    localStorage.removeItem(key)
  })
}
/**
 * 过滤对象中为空的属性，并删除对象中字符串属性值前后空格
 * @param obj
 * @returns {*}
 */
export function filterObj(obj) {
  if (!(typeof obj == 'object')) {
    return
  }

  for (var key in obj) {
    // eslint-disable-next-line no-prototype-builtins
    if (obj.hasOwnProperty(key) &&
      (obj[key] == null || obj[key] == undefined || obj[key] === '')) {
      delete obj[key]
      // eslint-disable-next-line no-prototype-builtins
    } else if (obj.hasOwnProperty(key) && (typeof (obj[key]) === 'string')) {
      obj[key] = obj[key].trim()
    }
  }
  return obj
}

const toType = (obj) => {
  return {}.toString
    .call(obj)
    .match(/\s([a-zA-Z]+)/)[1]
    .toLowerCase()
}

export const filterNull = (o) => {
  for (const k in o) {
    if (o[k] === null || o[k] === undefined) {
      delete o[k]
    }
    o[k] = toType(o[k]) === 'string' ? o[k].trim() : o[k]
    o[k] = ['object', 'array'].includes(toType(o[k])) ? filterNull(o[k]) : o[k]
  }
  return o
}

export const formatTime = (value, formatType = "YYYY-MM-DD") => {
  if (value) {
    return moment(value).format(formatType)
  } else {
    return '/'
  }
}

export const startTimeValue = (value) => {
  if (value) {
    return moment(value).startOf('day').valueOf()
  } else {
    return null
  }
}

export const endTimeValue = (value) => {
  if (value) {
    return moment(value).endOf('day').valueOf()
  } else {
    return null
  }
}

export const timeValue = (value) => {
  if (value) {
    return moment(value).valueOf()
  } else {
    return null
  }
}

export const beforeImgUpload = file => {
  const isImg = file.type.indexOf('image') >= 0
  if (!isImg) {
    message.error(t('other.onlyUploadImg') );
  }

  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error(t('other.imgMaxTen'));
  }

  return (isImg && isLt10M) || Upload.LIST_IGNORE;
};

export const getText = (ary, value, itemName = 'id') => {
  const info = ary.filter(i => i[itemName] == value)
  return info.length ? (info[0].label || info[0].name || '/') : '/'
}

export const getFieldText = (ary, value, itemName, field) => {
  const info = ary.filter(i => i[itemName] == value)
  return info.length ? info[0][field] : '/'
}

export const handleUploadImg = (info) => {
  console.log("info:::::", info)
  if (info.file.status !== 'uploading') {
    // console.log('uploading')
  }
  if (info.file.status === 'done') {
    if (info.file.response.success) {
      // message.success(`${info.file.name} 文件上传成功`)
    } else {
      message.error(info.file.response.msg)
    }
  } else if (info.file.status === 'error') {
    message.error(`${t('common.fileUploadErr')}: ${info.file.msg} `)
  }
}

export const getBaseUrl = (env) => {
  let url = env == 'devs' ? 'http://10.18.4.1:8051' : ''

  // switch (env) {
  //   case 'development':
  //     url = ''
  //     break
  //   case 'site':
  //     // url = 'http://localhost:8081'
  //     url = ''
  //     break
  //   case 'production':
  //     url = 'http://10.18.4.41:8082'
  //     break
  //   case 'devs':
  //     url = 'http://10.18.4.41:8081'
  //     break
  //   default:
  //     break
  // }
  return url
}

export const formatSeconds = (value) => {
  let theTime = parseInt(value) // 秒
  let middle = 0 // 分
  let hour = 0 // 小时

  if (theTime > 60) {
    middle = parseInt(theTime / 60)
    theTime = parseInt(theTime % 60)
    if (middle > 60) {
      hour = parseInt(middle / 60)
      middle = parseInt(middle % 60)
    }
  }
  let result = parseInt(theTime) ? "" + parseInt(theTime) + t('common.seconds') : (parseInt(middle) || parseInt(hour) ? '' : 0)
  if (middle > 0) {
    result = "" + parseInt(middle) + t('common.minute') + result
  }
  if (hour > 0) {
    result = "" + parseInt(hour) + "小时" + result
  }
  return result
}

// 驼峰命名转为下划线
export const toLineName = (name) => {
  return name.replace(/([A-Z])/g, "_$1").toLowerCase();
}

export const hasPermission = (ids) => {
  const permissionList = (getLocalStorage('buttonMenuList') || []).map(i => i.permission)
  const userInfo = getLocalStorage('user') || {}
  let flag = false
  if (userInfo.admin) {
    flag = true
  } else {
    if (Array.isArray(ids)) {
      flag = ids.some(i => permissionList.includes(i))
    } else if (typeof ids == 'string') {
      flag = permissionList.includes(ids)
    }
  }

  return flag
}